package com.aide.security.auth;

import java.io.Console;
import java.io.File;
import java.io.RandomAccessFile;

import com.aide.security.encoding.XXTEA;

public class AideCryptUtils {

	private static final char pk[] = { 'a', '8', 'i', '3', 'd', '2', 'e', '9' };

	public AideCryptUtils() {
	}

	public static String createSN(String key, String mac, String endDate) {
		String macc = "";
		try {
			macc = XXTEA.decrypt(mac, key);
		} catch (Exception e) {
			try {
				macc = XXTEA.decrypt(mac, "test");
				mac = XXTEA.encrypt(macc, key);
			} catch (Exception exception) {
			}
		}
		try {
			String info = XXTEA.encrypt(
					(new StringBuilder(String.valueOf(mac))).append("|")
							.append(XXTEA.encrypt(endDate, key)).toString(),
					new String(pk));
			return info;
		} catch (Exception e) {
			return (new StringBuilder("ERROR:")).append(key).append(":")
					.append(mac).toString();
		}
	}

	public static void main(String args[]) throws Exception {
		System.out.println(GetSNShell.getPhysicalAddress());
		File file = new File("sn_list.txt");
		Console cons = System.console();
		System.out.print("用户名：");
		String user = cons.readLine();
		System.out.print("机器码：");
		String mac = cons.readLine();
		if (mac == null || mac.trim().equals("")) {
			System.out.print("请输入MAC地址（以-分割）：");
			mac = cons.readLine();
			mac = XXTEA.encrypt(mac, user);
		}
		boolean flag = false;
		String date = "";
		while (!flag) {
			System.out.print("授权有效期（yyyy-MM-dd）：如2013-01-29 不输入默认2099-12-31");
			date = cons.readLine();
			if (date.equals(""))
				date = "2099-12-31";
			else
				date = date.trim();
			try {
				AideRead.df.setLenient(true);
				AideRead.df.parse(date);
				flag = true;
			} catch (Exception exception) {
			}
		}
		String sn = createSN(user, mac, date);
		RandomAccessFile randomFile = new RandomAccessFile(file, "rw");
		long fileLength = randomFile.length();
		randomFile.seek(fileLength);
		String line = (new StringBuilder("用户名：")).append(user).append("|机器码：")
				.append(mac).append("|授权有效期：").append(date).append("|序列号：")
				.append(sn).append("\r\n").toString();
		randomFile.writeBytes(line);
		randomFile.close();
		System.out.println((new StringBuilder("序列号：")).append(sn).toString());
	}

}